<template>
	<view class="container" :data-theme="theme">
		<view class="header">
			<view class="header-title">
				促销价设置仅支持售卖中商品，单次最多提交10个商品
			</view>
			<!-- 设置活动内容 -->
			<view class="activity-view">
				<!-- 活动时间 -->
				<view class="active-time">
					<view class="active-time-title">
						活动时间
					</view>
					<view class="active-date">
						<view class="active-date-left">活动时间</view>
						<view class="active-date-right">
							<uni-datetime-picker v-model="depreciatePromotion.activityTimeList" type="daterange"
								@change="changeActiveTime">
								<view v-if="depreciatePromotion.activeTime">{{depreciatePromotion.activeTime}}
								</view>
								<view v-else>请选择活动时间</view>
							</uni-datetime-picker>
							<u-icon name="arrow-right"></u-icon>
						</view>

					</view>
				</view>
				<!-- 活动限制 -->
				<view class="active-limit">
					<view class="active-limit-title">
						活动限制
					</view>
					<!-- 促销总库存 -->
					<view class="active-limit-card">
						<view class="active-limit-top">
							<view class="active-limit-left">促销总库存</view>
							<view class="active-limit-right">
								<radio-group style="display: flex;" @change="inventoryChange">
									<view class="radio" v-for="(item,index) in radiolist1" :key="index">
										<view style="margin-left: 60rpx;">
											<radio :value="item.disabled.toString()"
												:checked="item.disabled == depreciatePromotion.activeLimit.inventory" />
											{{item.name}}
										</view>
									</view>
								</radio-group>
							</view>
						</view>
						<view class="active-limit-bottom" v-if="!depreciatePromotion.activeLimit.inventory">
							<uni-number-box v-model="depreciatePromotion.activeLimit.inventoryNum"
								@change="generalInventoryFun" :min='0' :max="Infinity" />
						</view>
					</view>
					<!-- 客户单日限购 -->
					<view class="active-limit-card">
						<view class="active-limit-top">
							<view class="active-limit-left">客户单日限购</view>
							<view class="active-limit-right">
								<radio-group style="display: flex;" @change="dateLimitShopChange">
									<view class="radio" v-for="(item,index) in radiolist2" :key="index">
										<view style="margin-left: 60rpx;">
											<radio :value="item.disabled.toString()"
												:checked="item.disabled == depreciatePromotion.activeLimit.dateLimitShop" />
											{{item.name}}
										</view>
									</view>
								</radio-group>
							</view>
						</view>
						<view class="active-limit-bottom" v-if="!depreciatePromotion.activeLimit.dateLimitShop">
							<uni-number-box v-model="depreciatePromotion.activeLimit.dateLimitShopNum"
								@change="generalInventoryFun" :min='0' :max="Infinity" />
						</view>
						<view class="hint-bottom" v-if="depreciatePromotion.activeLimit.dateLimitShopNumIsShow">
							促销总库存必须大于等于客户单日限购
						</view>
					</view>
				</view>
				<view class="active-time"
					v-if="propsData && propsData.enrolledActivityProductVoList  && propsData.enrolledActivityProductVoList.length">
					<view class="active-time-title">
						活动商品
					</view>
				</view>
			</view>
		</view>
		<view class="content">
			<!-- 这里是可滚动的内容 -->
			<scroll-view class="scroll-view" scroll-y>
				<view class="scroll-view-inner">
					<detail-product-page class="swiper-page" :bgColor="bgColor" ref="tab"
						:ongoingProductList="propsData" :activityCategory="activityCategory" @toDetails="toDetails"
						@changeActive="changeActive" @deleteEnrolledPro="deleteEnrolledPro"></detail-product-page>
				</view>
			</scroll-view>
		</view>
		<view class="footer">
			<checkbox-group @change="requiredChange">
				<label class="footer-required">
					<view>
						<checkbox :checked="required" />
					</view>
					<view>已阅读并同意 <span class="font_color">《合作商自营销协议》</span> </view>
				</label>
			</checkbox-group>
			<view class="footer-button"
				v-if="propsData &&  propsData.enrolledActivityProductVoList   && propsData.enrolledActivityProductVoList.length">
				<button class="bg_color" @click="handleUpdateActivity" shape="circle">修改活动信息</button>
				<button class="bg_color" @click="handleNext" shape="circle">选择商品</button>
			</view>
			<button class="bg_color" @click="handleNext" shape="circle" style="padding: 20rpx;" v-else>下一步，选择商品</button>
		</view>
	</view>
</template>
<script>
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	import {
		getNoRegistrationActivityApi,
		addActivityRegistrationApi
	} from "@/api/marketing.js"
	import detailProductPage from "./components/detail-product-page"
	let app = getApp()
	export default {
		components: {
			detailProductPage
		},
		data() {
			return {
				bgColor: "#fff",
				theme: app.globalData.theme,
				num: 1,
				depreciatePromotion: {
					activityTimeList: [], // 后端所需要的时间数组
					activeTime: null, // 活动时间
					activeLimit: {
						inventory: true, // 库存
						inventoryNum: '20', // 库存自定义数量
						dateLimitShopNum: '20', // 日限购 自定义数量
						dateLimitShop: true, // 日限购
						dateLimitShopNumIsShow: false, // 日限购提示信息
					}
				},
				// 库存
				radiolist1: [{
						name: '不限',
						disabled: true
					},
					{
						name: '自定义',
						disabled: false
					}
				],
				// 日限购 
				radiolist2: [{
						name: '不限',
						disabled: true
					},
					{
						name: '自定义',
						disabled: false
					}
				],
				required: false, //必选事件
				// ---------------------------活动商品---------------------
				tabList: [{
					name: '活动中',
					type: 1,
				}, {
					name: '未生效',
					type: 2,
				}],
				propsData: {}, //给子组件传的值
				activityCategory: 0, //活动类型
			}
		},
		onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			this.initData()
		},
		methods: {
			// 初始化数据
			initData() {
				this.getNoRegistrationActivity()
			},
			// 回显数据
			echoData() {
				if (this.propsData && this.propsData.enrolledActivityProductVoList && this.propsData
					.enrolledActivityProductVoList.length) {
					// 回显时间
					let timeList = this.propsData.activityTimeList
					this.depreciatePromotion.activityTimeList = timeList
					this.depreciatePromotion.activeTime = timeList[0].slice(0, 10) + '至' + timeList[1].slice(0, 10) + '(' +
						this
						.calculateDaysBetweenDates(timeList[0], timeList[
							1]) + '天)'
					// 回显活动限制
					// 活动促销总库存
					if (this.propsData.promotionInventory == -1) {
						this.depreciatePromotion.activeLimit.inventory = true
					} else {
						this.depreciatePromotion.activeLimit.inventory = false
						this.$set(this.depreciatePromotion.activeLimit, 'inventoryNum', this.propsData.promotionInventory)
						// this.depreciatePromotion.activeLimit.inventoryNum = this.propsData.promotionInventory
					}
					// 活动客户单日限购
					if (this.propsData.customerDailyLimit == -1) {
						this.depreciatePromotion.activeLimit.dateLimitShop = true
					} else {
						this.depreciatePromotion.activeLimit.dateLimitShop = false
						this.$set(this.depreciatePromotion.activeLimit, 'dateLimitShopNum', this.propsData
							.customerDailyLimit)
						// this.depreciatePromotion.activeLimit.dateLimitShopNum = this.propsData.customerDailyLimit
					}
				}
			},
			// ---------------------------添加过的活动商品------------------------------


			toDetails(item) {
				console.log("item", item)
				this.goPage(
					`/pages/marketing/depreciatePromotionList/components/productDetail?type=${1}&productInfo=${JSON.stringify(item)}`
				)
			},
			goPage(url) {
				uni.navigateTo({
					url
				});
			},
			// ---------------------------end---------------------------------
			calculateDaysBetweenDates(date1Str, date2Str) {
				// 将日期字符串转换为 Date 对象
				var date1 = new Date(date1Str);
				var date2 = new Date(date2Str);

				// 计算两个日期的时间戳（单位：毫秒）
				var time1 = date1.getTime();
				var time2 = date2.getTime();

				// 确保 date1 <= date2，如果不是，则交换两个日期
				if (time1 > time2) {
					var temp = date1;
					date1 = date2;
					date2 = temp;
				}

				// 设置 date1 的时分秒为 00:00:00
				date1.setHours(0, 0, 0, 0);

				// 设置 date2 的时分秒为 00:00:00，并将日期加一天，用于确保计算包含 date2 这一天
				date2.setHours(0, 0, 0, 0);
				date2.setDate(date2.getDate() + 1);

				// 计算两个日期之间的天数差
				var timeDiff = date2.getTime() - date1.getTime();
				var daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

				return daysDiff;
			},
			// 改变活动时间
			changeActiveTime(e) {
				this.depreciatePromotion.activeTime = e[0] + '至' + e[1] + '(' + this.calculateDaysBetweenDates(e[0], e[
					1]) + '天)'
				this.depreciatePromotion.activityTimeList = (e[0] + ' 00:00:00' + ',' +
					e[1] + ' 23:59:59').split(",")
			},
			// 改变促销总库存数量
			inventoryChange(e) {
				if (e.detail.value == 'true') {
					this.depreciatePromotion.activeLimit.inventory = true
					// this.depreciatePromotion.activeLimit.inventoryNum = ''
				} else if (e.detail.value == 'false') {
					this.depreciatePromotion.activeLimit.inventory = false
				}
				// 促销总库存必须大于等于客户单日限购
				this.generalInventoryFun()
			},
			// 改变客户单日限购
			dateLimitShopChange(e) {
				if (e.detail.value == 'true') {
					this.depreciatePromotion.activeLimit.dateLimitShop = true
					// this.depreciatePromotion.activeLimit.dateLimitShopNum = ''

				} else if (e.detail.value == 'false') {
					this.depreciatePromotion.activeLimit.dateLimitShop = false
				}
				// 促销总库存必须大于等于客户单日限购
				this.generalInventoryFun()
			},

			//通用促销总库存必须大于等于客户单日限购(不限数量也要考虑)
			generalInventoryFun() {
				let exceedPromotionPrice = this.depreciatePromotion.activeLimit
				if (((Number(exceedPromotionPrice.inventoryNum) < Number(exceedPromotionPrice.dateLimitShopNum) && !
						exceedPromotionPrice.inventory)) || (exceedPromotionPrice.dateLimitShop && !exceedPromotionPrice
						.inventory)) {
					this.depreciatePromotion.activeLimit.dateLimitShopNumIsShow = true
				} else {
					this.depreciatePromotion.activeLimit.dateLimitShopNumIsShow = false
				}
			},
			// 必选事件
			requiredChange(val) {
				this.required ? this.required = false : this.required = true
			},

			// 下一步，选择商品
			handleNext() {
				if (!this.depreciatePromotion.activeTime) {
					return uni.showToast({
						title: '请选择活动时间',
						duration: 1500,
						icon: 'none'
					});
				}
				if (!this.required) {
					return uni.showToast({
						title: '请先阅读并同意《合作商自营销协议》',
						duration: 1500,
						icon: 'none'
					});
				}
				if (this.depreciatePromotion.activeLimit.dateLimitShopNumIsShow) {
					return uni.showToast({
						title: '请完成校验',
						duration: 1500,
						icon: 'none'
					});
				}
				// 判断有没有活动
				if (this.propsData && this.propsData.enrolledActivityProductVoList) {
					this.depreciatePromotion.activityStatus = true // 有活动需要传递id
					this.depreciatePromotion.id = this.propsData.id
				} else {
					this.depreciatePromotion.activityStatus = false
					this.depreciatePromotion.id = null
				}
				uni.navigateTo({
					url: `/pages/marketing/depreciatePromotionList/promotionProductList?depreciatePromotion=${JSON.stringify(this.depreciatePromotion)}`,
				});
			},
			// 修改活动信息
			handleUpdateActivity() {
				let that = this
				if (!this.depreciatePromotion.activeTime) {
					return uni.showToast({
						title: '请选择活动时间',
						duration: 1500,
						icon: 'none'
					});
				}
				if (!this.required) {
					return uni.showToast({
						title: '请先阅读并同意《合作商自营销协议》',
						duration: 1500,
						icon: 'none'
					});
				}
				if (this.depreciatePromotion.activeLimit.dateLimitShopNumIsShow) {
					return uni.showToast({
						title: '请完成校验',
						duration: 1500,
						icon: 'none'
					});
				}
				uni.showModal({
					title: '提示',
					content: '确认修改活动信息吗？',
					success(res) {
						if (res.confirm == true) {
							that.updateActivityRegistration()
						} else {
							uni.showToast({
								title: '已取消修改',
								duration: 2000,
								icon: 'none'
							})
						}
					},
				})
			},

			// ----------------------api--------------------------------
			// 修改活动信息
			async updateActivityRegistration() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let data = {
					id: this.propsData.id,
					activityCategory: 6,
					activityTimeList: this.depreciatePromotion.activityTimeList,
					promotionInventory: this.depreciatePromotion.activeLimit.inventory ? -1 : this
						.depreciatePromotion.activeLimit.inventoryNum,
					customerDailyLimit: this.depreciatePromotion.activeLimit.dateLimitShop ? -1 : this
						.depreciatePromotion.activeLimit.dateLimitShopNum,
				}
				try {
					let res = await addActivityRegistrationApi(data)
					if (res.code == 200) {
						this.getNoRegistrationActivity()
						uni.showToast({
							title: '修改成功',
							icon: 'none',
							duration: 2000
						})
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 2000
						});
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: e,
						duration: 2000,
						icon: 'none'
					})
				}
				uni.hideLoading()
			},
			// 获取活动商品数据
			async getNoRegistrationActivity() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				try {
					let res = await getNoRegistrationActivityApi(6)
					if (res.code == 200) {
						this.propsData = res.data
						if (res.data == null && res.data.enrolledActivityProductVoList && res.data
							.enrolledActivityProductVoList.length) {
							uni.hideLoading()
							return
						}
						// 回显数据
						this.echoData()
						// 将外层时间等数据都放到每一个商品数组对象中
						this.propsData.enrolledActivityProductVoList = res.data.enrolledActivityProductVoList.map(
							item => {
								return {
									...item,
									activityTimeList: res.data.activityTimeList,
									activityId: res.data.id,
									activityScopeList: res.data.activityScopeList,
									activitySubsidyList: res.data.activitySubsidyList,
									activityCustomerDailyLimit: res.data.customerDailyLimit,
									productScope: res.data.productScope,
									activityTotalOrderLimit: res.data.totalOrderLimit,
									activityPromotionInventory: res.data.promotionInventory,
									activityTime: this.depreciatePromotion.activeTime,
									status: res.data.status
								}
							})

					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 2000
						});
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: e,
						duration: 2000,
						icon: 'none'
					})
				}
				uni.hideLoading()
			},
		},

	}
</script>
<style lang="scss">
	page {
		height: 100%;


	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		.header-title {
			padding: 20rpx;
			background-color: #fff1f3;
			color: #e07f6e;
		}
	}

	.content {
		flex: 1;
		overflow: hidden;
		margin: 0 20rpx;
	}

	.scroll-view {
		height: 100%;
	}

	.scroll-view-inner {
		margin: 20rpx;
		background-color: white;
	}

	.activity-view {

		// 活动时间
		.active-time {
			display: flex;
			flex-direction: column;
			padding: 20rpx;

			.active-time-title {
				padding: 20rpx 0;
				font-weight: bold;
				font-size: 35rpx;

			}

			.active-date {
				display: flex;
				justify-content: space-between;
				background-color: white;
				padding: 30rpx 20rpx;
				border-radius: 10rpx;

				.active-date-left {}

				.active-date-right {
					display: flex;
				}
			}
		}

		// 活动限制
		.active-limit {
			display: flex;
			flex-direction: column;
			padding: 20rpx;

			.active-limit-title {
				padding: 20rpx 0;
				font-weight: bold;
				font-size: 35rpx;
			}

			.active-limit-card {
				display: flex;
				flex-direction: column;
				background-color: white;
				padding: 30rpx 20rpx;
				border-radius: 10rpx;

				.active-limit-top {
					display: flex;
					justify-content: space-between;

					.active-limit-left {}

					.active-limit-right {}
				}

				.active-limit-bottom {
					display: flex;
					display: flex;
					justify-content: flex-end;
					padding: 20rpx 0;
				}

				.hint-bottom {
					display: flex;
					justify-content: flex-end;
					padding: 20rpx 0;
					color: red;
				}

			}

		}
	}

	.footer {
		.bg_color {
			@include main_bg_color(theme);
			color: white;
		}

		.font_color {
			@include main_color(theme)
		}

		.footer-button {
			display: flex;
			justify-content: space-between;

			button {
				padding: 20rpx;
				width: 48%;
			}
		}

		.footer-required {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
		}

		background-color: white;
		padding: 20rpx;
	}

	// ----------活动商品---------------
	.card {
		margin: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
	}

	.header-top {
		display: flex;
		justify-content: space-between;
	}

	.header_name {
		font-size: 31rpx;
		font-weight: bolder;
	}

	.border-item {
		border-bottom: 1px solid #f3f3f3;
	}

	.swiper-item {
		flex: 1;
		flex-direction: column;
	}

	.swiper-page {
		flex: 1;
		flex-direction: column;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}

	.tab-view {
		display: flex;
		flex-direction: column;
		flex: 1;
		height: 820rpx;

		.scroll-view {
			height: 100%;
		}
	}
</style>